﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using TravelAgencyDAL;
using System.Drawing;
using System.IO;

namespace TravelAgencyHTML5
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : ITravelAgencyService
    {
        private const int PAGE_SIZE = 12;
        private TravelAgencyDAO dao = new TravelAgencyDAO();

        public IEnumerable<TripDTO> GetTrips(string page)
        {
            int requestedPage = int.Parse(page);
            var trips = dao.GetTripsByPage(PAGE_SIZE, requestedPage);
            var tripDtos = ConvertToTripDTO(trips);
            return tripDtos;
        }

        public Image GetImage(string imageId)
        {
            int selectedImage = int.Parse(imageId);
            Photo photo = dao.GetPhotoByPhotoId(selectedImage);
            using (MemoryStream ms = new MemoryStream(photo.PhotoContent))
            {
                Image returnImage = Image.FromStream(ms);
                return returnImage;
            }
        }

        public TripDetailsDTO GetTripDetails(string id)
        {
            int tripId = int.Parse(id);
            Trip trip = dao.GetTripByTripId(tripId);
            TripDetailsDTO tripDtos = ConvertToTripDetailsDTO(trip);
            return tripDtos;
        }

        public void CreateReservation(WebReservation newReservation)
        {
            dao.AddReservation(newReservation.UserName, newReservation.TripId, newReservation.PeopleCount);
        }

        public static IEnumerable<TripDTO> ConvertToTripDTO(IEnumerable<Trip> trips)
        {
            List<TripDTO> converted = new List<TripDTO>();
            foreach (var trip in trips)
            {
                TripDTO toAdd = new TripDTO {Id = trip.TripId, Title = trip.Title,
                                             StartDate = trip.StartDate,
                                             EndDate = trip.EndDate,
                                             PhotoId = trip.PhotoId
                };
                converted.Add(toAdd);
            }
            return converted;
        }

        public static TripDetailsDTO ConvertToTripDetailsDTO(Trip trip)
        {
            TripDetailsDTO converted = new TripDetailsDTO
            {   
                AvailableRooms = trip.MaxPeopleCapacity - trip.CurrentPeopleCapacity,
                Discription = trip.Description,
                Price = trip.Price,
                Title = trip.Title,
                StartDate = trip.StartDate,
                EndDate = trip.EndDate,
                PhotoId= trip.PhotoId
            };
            return converted;
        }
    }
}
